<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    function Axios(config) {
        this.config = config
        this.interceptors = {
            request: new InterceptorManager(),
            response: new InterceptorManager()
        }
    }
    function InterceptorManager() {
        this.handles = []
    }
    Axios.prototype.request = function (config){

        let promise = Promise.resolve(config);

        let chains = [dispatchRequest,undefined]

        // 处理请求拦截
       this.interceptors.request.handles.forEach(item =>{
            chains.unshift(item.fulfilled,item.reject)
       })
        this.interceptors.response.handles.forEach(item=>{
            chains.push(item.fulfilled,item.reject)
        })

        console.log(chains)

        while (chains.length){
            promise = promise.then(chains.shift(),chains.shift())
        }

        return promise

    }
    function dispatchRequest(){
        return new Promise(((resolve, reject) => {
            resolve({
                status: 5,
                statusText: 'OK'
            })
        }))
    }
    function createInstance(config){
        let context = new Axios(config)
        let instance = Axios.prototype.request.bind(context)
        for (let key in context) {
            instance[key] = context[key]
        }
        // for (let key in Axios.prototype) {
        //     instance[key] = Axios.prototype[key]
        // }
        console.dir(instance)
        return instance
    }
    // 保存拦截器回调
    InterceptorManager.prototype.use = function (fulfilled, reject) {
        this.handles.push({
            fulfilled,
            reject
        })
    }

    let axios = createInstance({});

    axios.interceptors.request.use(function (config){
        console.log('请求拦截器 成功 -1 ')
        return config
    },function (error){
        console.log('请求拦截器 失败 -1 ')
        return Promise.reject(error)
    })
    axios.interceptors.request.use(function (config){
        console.log('请求拦截器 成功 -2 ')
        return config
    },function (error){
        console.log('请求拦截器 失败 -2 ')
        return Promise.reject(error)
    })
    axios.interceptors.response.use(function (response){
        console.log('响应拦截器 成功 -1')
        return response
    },function (error){
        console.log('响应拦截器 失败 -1')
        return Promise.reject(error)
    })
    axios.interceptors.response.use(function (response){
        console.log('响应拦截器 成功 -2')
        return response
    },function (error){
        console.log('响应拦截器 失败 -2')
        return Promise.reject(error)
    })

    axios().then(value => {
        console.log(value)
    })
</script>
</body>
</html>